<?php
//begin session
require 'session.php';

if (empty($_GET['realm'])||empty($_GET['guild']))
{
	header('Location: index.php');
}

//Check if logged in
include 'loginoptional.php';
include 'api.php';
include 'connect_pdo.php';
echo "<a href='index.php' class='reg'>Back</a>";
try{
	echo "<p>I just added a whole bunch of people to track!<br/><br/>";
	
	$realm = $_GET['realm'];
	$guild = $_GET['guild'];
	$realm = stripslashes($realm);
	$guild = stripslashes($guild);

	$data = $api->getGuildApi()->getGuild($realm, $guild, true);

	$guildMembers = $data['members'];

	foreach($guildMembers as $member)//loop through all the members
	{
	$char = $member['character']['name'];
				
	$sqlFindChar = "SELECT char_id FROM char_summary WHERE upper(name) like upper('$char') and upper(realm) like 				upper('$realm')";
	$sqlInsertChar = "INSERT into char_summary (name, realm, datestamp, userstamp) values (:char,:realm, (select now()), 1)";//race class and faction are done later
	$sqlHistRow = "SELECT char_history_id FROM char_history WHERE char_id=:charId AND datestamp = (select curdate())";
	
	$STH = $DBH->prepare($sqlFindChar);
	$STH->execute();
	$count = $STH->rowCount();
	$result = $STH->fetch();
	
	if ($count<1)
	{
		try{
		$STH = $DBH->prepare($sqlInsertChar);
		$STH->bindParam(':char', $char);
		$STH->bindParam(':realm', $realm);
		$STH->execute();
		$charId = $DBH->lastInsertId();
		
		$STH = $DBH->prepare($sqlHistRow);
		$STH->bindParam(':charId', $charId);
		$STH->execute();
		
		}
		catch (exception $e)
		{
		echo 'Error adding character: ', $e->getMessage();
		}
		echo "Character $charId added ($char)<br/>";
		
		
	
	
	}
	else
	{
	echo "$char is already being tracked<br/>";
	}
	
	}
echo "</p>";
}
catch (exception $e)
{
	echo 'Error retrieving realm data: ', $e->getMessage();


}
echo "<a href='index.php' class='reg'>Back</a>";
include 'footer.html';
?>